package com.teamsun.redis;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * <p>序列化/反序列化公共方法</p>
 */
public class SerializeUtil {

    /**
     * 对象序列化
     * @param object
     * @return
     */
    public static byte[] serialize(Object object) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Hessian2Output hessian2Output = new Hessian2Output(baos);
        hessian2Output.writeObject(object);
        baos.close();
        hessian2Output.close();

        return baos.toByteArray();
    }

    /**
     * 对象反序列化
     * @param bytes
     * @return
     */
    public static Object unSerialize(byte[] bytes) throws Exception {
        Object object = null;
        if(bytes != null) {
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            Hessian2Input hessian2Input = new Hessian2Input(bais);
            object = hessian2Input.readObject();
            bais.close();
            hessian2Input.close();
        }

        return object;
    }
}
